﻿using DnsClient;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Resilience;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using User.Identity.Dtos;
using static Microsoft.AspNetCore.WebSockets.Internal.Constants;

namespace User.Identity.Service
{
    public class UserService : IUserService

    {
        private IHttpClient _httpClient;
        private readonly string _userServiceUrl;// = "http://localhost:91/";
        private readonly ILogger<UserService> _logger;
        public UserService(IHttpClient httpClient, IOptions<ServiceDisvoveryOptions> serviceDisvoveryOptions, IDnsQuery dnsQuery,
             ILogger<UserService> logger)
        {
            _httpClient = httpClient;
            //基于服务发现获取地址
            var address = dnsQuery.ResolveService("service.consul", serviceDisvoveryOptions.Value.UserServiceName);
            var addressList = address.First().AddressList;
            var host = addressList.Any() ? addressList.First().ToString().TrimEnd('.') : address.First().HostName.TrimEnd('.');
            var port = address.First().Port;
            _userServiceUrl = $"http://{host}:{port}";
            _logger = logger;
        }
        public async Task<int> CheckOrCreate(string phone)
        {
            var from = new Dictionary<string, string>
            {
                { "phone", phone }
            };
            // var content = new FormUrlEncodedContent(from);

            //  content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); 

            var form = new Dictionary<string, string> { { "phone",phone} };

            try
            {
                var response = await _httpClient.PostAsync(_userServiceUrl + "/api/User/check-or-create", form);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    int.TryParse(await response.Content.ReadAsStringAsync(), out int userId);
                    return userId;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("CheckOrCreate 再重试之后失败," + ex.Message + ex.StackTrace);
                throw ex;
            }
            return 0;
        }
    }
}
